package com.quectel.core.module.partyeducationexam.service.impl;


import com.google.common.base.Preconditions;
import com.quectel.constant.core.partyeducationexam.PartyEducationQuestionBankConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partyeducationexam.dao.PartyEducationQuestionBankDao;
import com.quectel.core.module.partyeducationexam.dto.PartyEducationQuestionBankDto;
import com.quectel.core.module.partyeducationexam.dto.PartyEducationQuestionBankPartyDto;
import com.quectel.core.module.partyeducationexam.entity.PartyEducationQuestionBankEntity;
import com.quectel.core.module.partyeducationexam.service.PartyEducationQuestionBankPartyService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationQuestionBankService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationQuestionService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/06/16 15:12
 */
@DubboService
public class PartyEducationQuestionBankServiceImpl implements PartyEducationQuestionBankService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyEducationQuestionBankServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_EDUCATION_QUESTION_BANK_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_EDUCATION_QUESTION_BANK_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyEducationQuestionBankDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_EDUCATION_QUESTION_BANK_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyEducationQuestionBankDao partyEducationQuestionBankDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyEducationQuestionBankPartyService partyEducationQuestionBankPartyService;
    @Autowired
    private PartyEducationQuestionService partyEducationQuestionService;

    @Override
    @Transactional
    public void saveAndUpdate(PartyEducationQuestionBankDto dto) {
        Long id = dto.getId();
        if (Objects.isNull(id)) {
            id = save(dto);
        } else {
            updateById(dto);
        }

        final Long dtoId = id;
        partyEducationQuestionBankPartyService.deleteByBankId(dto.getId());
        if (PartyEducationQuestionBankConstants.PrivacyTypeEnum.PUBLIC.getPrivacyType().equals(dto.getPrivacyType())) {
            Preconditions.checkNotNull(dto.getPartyIds());

            List<PartyEducationQuestionBankPartyDto> dtos = Arrays.stream(dto.getPartyIds()).parallel().map(o -> {
                PartyEducationQuestionBankPartyDto newlyDto = new PartyEducationQuestionBankPartyDto();
                newlyDto.setBankId(dtoId);
                newlyDto.setPartyId(o);
                return newlyDto;
            }).collect(Collectors.toList());
            partyEducationQuestionBankPartyService.saveBatch(dtos);
        }
    }

    @Override
    public PartyEducationQuestionBankDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_EDUCATION_QUESTION_BANK_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyEducationQuestionBankDto selectById(Long id){
            PartyEducationQuestionBankEntity entity = partyEducationQuestionBankDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyEducationQuestionBankDto.class));
    }

    @Override
    public List<PartyEducationQuestionBankDto> queryList(Map<String,Object> params){
        List<PartyEducationQuestionBankEntity> list = partyEducationQuestionBankDao.queryList(params);
        List<PartyEducationQuestionBankDto> result =  CopyUtils.copyList(list,PartyEducationQuestionBankDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<PartyEducationQuestionBankDto> queryListWithoutPadding(Map<String,Object> params){
        List<PartyEducationQuestionBankEntity> list = partyEducationQuestionBankDao.queryList(params);
        return CopyUtils.copyList(list,PartyEducationQuestionBankDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyEducationQuestionBankDto paddingField(PartyEducationQuestionBankDto dto){
        if (dto != null){
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);

            if (PartyEducationQuestionBankConstants.PrivacyTypeEnum.PUBLIC.getPrivacyType().equals(dto.getPrivacyType())) {
                List<PartyEducationQuestionBankPartyDto> partyEducationQuestionBankPartyDtos =  partyEducationQuestionBankPartyService.selectByBankId(dto.getId());
                Long[] partyIds = partyEducationQuestionBankPartyDtos.parallelStream().map(PartyEducationQuestionBankPartyDto::getPartyId).toArray(Long[]::new);
                dto.setPartyIds(partyIds);
            }

            int count = partyEducationQuestionService.queryTotalByBankId(dto.getId());
            dto.setQuestionCount(count);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyEducationQuestionBankDao.queryTotal(params);
    }

    @Override
    public Long save(PartyEducationQuestionBankDto dto){
        PartyEducationQuestionBankEntity entity = CopyUtils.copyObj(dto,PartyEducationQuestionBankEntity.class);
        entity.setId(Snowflake.nextId());
        partyEducationQuestionBankDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyEducationQuestionBankDto dto){
        PartyEducationQuestionBankEntity entity = CopyUtils.copyObj(dto,PartyEducationQuestionBankEntity.class);

        partyEducationQuestionBankDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyEducationQuestionBankDto dto) {
       PartyEducationQuestionBankEntity entity = CopyUtils.copyObj(dto,PartyEducationQuestionBankEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyEducationQuestionBankDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Transactional
    public void deleteById(Long id){

        PartyEducationQuestionBankDto partyEducationQuestionBankDto = selectById(id);
        CLEAR_CACHE_FUNC.accept(partyEducationQuestionBankDto);

        partyEducationQuestionBankDao.deleteById(id);

        if (PartyEducationQuestionBankConstants.PrivacyTypeEnum.PUBLIC.getPrivacyType().equals(partyEducationQuestionBankDto.getPrivacyType())) {
            partyEducationQuestionBankPartyService.deleteByBankId(partyEducationQuestionBankDto.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
